package Controller;

import entity.User;
import service.impl.UserServiceImpl;
import service.UserService;
import util.Constants;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
 *86180
 *2021/10/2
 *19:01
 */
@WebServlet("/user")
public class UserController extends BaseController {
    public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("测试收参"+username+" "+password);

        UserService userService=new UserServiceImpl();
        User user = userService.login(username, password);
        System.out.println(user);
        if(user!=null){
            System.out.println("测试名字密码正确");
            request.getSession().setAttribute("user", user);
            return Constants.REDIRECT+"/index.jsp";
        }else{
            System.out.println("测试名字密码错误");
            return Constants.REDIRECT+"/login.jsp";
        }
    }

    public String exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().removeAttribute("user");
        System.out.println("退出注销成功");
        return Constants.REDIRECT+"/login.jsp";
    }

    public void checkPwd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String oldPwd = request.getParameter("oldPwd");
        User user=(User)request.getSession().getAttribute("user");
        if(user.getPassword().equals(oldPwd)){
            response.getWriter().println(1);
        }else{
            response.getWriter().println(0);
        }
    }

    public void updatePwd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String newPwd = request.getParameter("newPwd");
        User user=(User)request.getSession().getAttribute("user");
        UserService userService=new UserServiceImpl();
        int i = userService.updatePassword(user.getUsername(), newPwd);
        response.getWriter().println(i);
    }


}
